// 待发货
var tblWaitSendOutGoods;
// 发货中
var tblSendingOutGoods;
// 已系统发货
var tblShiped;
// 已平台发货
var tblConsigned;
// 已取消
var tblCanceled;
// 高级检索条件
var searchCondition = {
    "cons":"",
    "consMobile":"",
    "shopId":"",
    "paidDateStart":"",
    "paidDateEnd":"",
    "lgstNo":"",
    "storId":"",
    "goodsCode":"",
    "goodsName":"",
    "skuCode":"",
    "skuName":"",
    "dateType":"",
    "sendDateStart":"",
    "sendDatend":""
};

//初始化iCheck组件
turn_on_iCheck = function(domElement) {
    return $('input[type="checkbox"],input[type="radio"]', domElement).iCheck({
        checkboxClass : 'icheckbox_flat-red',
        radioClass : 'iradio_flat-red'
    });
};

$(document).ready(function () {
    
    $('.panel-default .datetimepicker-default').datetimepicker();
    
    // 默认待发货显示
    getWaitSendOutGoods();
    
    getCounts();
    
    $("#btnBatchCancelSystemSend").show();
    $("#batchConsign").hide();
    // 按钮控制
    setPageElementStatus("shiporderList");
    // 构建店铺下拉列表 
    $.ajax({
        type: "GET",
        url: "/shop/unpagedShopList.action?prjId=" + window.top.window.$("#projectSwitch").val(),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data.result == "success") {
                $("#shopId option").remove();
                $("#shopId").append("<option value=''>请选择</option>");
                $.each(data.data, function (n, value) {
                    $('#shopId').append("<option value='" + value.shopId + "'>" + value.shopName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
    
    // 构建第三方仓库下拉列表 
    $.ajax({
        type: "GET",
        url: "/stor/storList.action?length=-1&storType=local",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data.result == "success") {
                $("#storId option").remove();
                $("#storId").append("<option value=''>请选择</option>");
                $.each(data.data, function (n, value) {
                    $('#storId').append("<option value='" + value.storId + "'>" + value.storName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

    $('#dateType').on('change',function() {

        switch (this.value) {
            case "付款时间": //
                $("#sendStart").hide()
                $("#sendEnd").hide()
                $("#sendDateStart").val();
                $("#sendDatend").val();

                $("#paidStart").show()
                $("#paidEnd").show()
                break;

            case "发货时间":
                $("#sendStart").show()
                $("#sendEnd").show()

                $("#paidStart").hide()
                $("#paidEnd").hide()
                $("#paidDateStart").val();
                $("#paidDatend").val();
                break;
            default:
        }
    });

    // 对话框关闭事件发生
    $('#frmModifyShipOrder').on('hide.bs.modal', function() {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    })

    /**
     * 修改
     */
    $("#btnModify").click(function() {
        if(!$('#frmModifyShipOrder',window.top.document).find("#frmOrderAssign").valid()) {
            $("#btnModify").click();
            return;
        }

        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
        var shiporder = new Object();
        shiporder.shiporderId = $("#shipOrderIdModify").val();
        shiporder.cons = $("#consModify").val();
        shiporder.consTel = $("#consTelModify").val();
        shiporder.consMobile = $("#consMobileModify").val();
        shiporder.consAddr = $("#consAddrModify").val();
        shiporder.lgstNo = $("#lgstnoModify").val();
        if ($("#lgstIdShipModify").val() != '') {
            shiporder.lgstId = $("#lgstIdShipModify").val();
            shiporder.lgstName = $("#lgstIdShipModify").find("option:selected").text();
            shiporder.lgstCode = $("#lgstIdShipModify").find("option:selected").attr("lgstCode");
        }

        $.ajax({
            type : "POST",
            url : "/localshiporder/updateShipOrder.action",
            data : JSON.stringify(shiporder),
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            async : true, // 同步
            success : function(data) {
                if (data.result == "y") {
                    window.top.window.showModalAlert("保存成功");
                    $('#frmModifyShipOrder').modal('hide');
                } else {
                    window.top.window.borrowCustomModalDialog($("#assignOrderPage"));
                    if (data.msg!="" && data.msg!=null && data.msg!=undefined){
                        var editDialog = window.top.window.borrowCustomModalDialog($("#frmModifyShipOrder"));
                        editDialog.modal({
                            show : true,
                            backdrop : 'static'
                        });
                        window.top.window.showModalAlert(data.msg);
                    }
                }
                refresh();
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });

    });

});

//修改发货单
function operationUPdate(btn,id) {
    // 物流公司 初期化
    $.ajax({
        type : "GET",
        url : "/lgst/getLgstByProjectId.action?projectId=" + window.top.window.$("#projectSwitch").val(),
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        async : false,// 同步
        success : function(data) {
            if (data.result == "success") {
                $("#lgstIdShipModify option").remove();
                $("#lgstIdShipModify").append("<option value=''>请选择</option>");
                $.each(data.data, function(n, value) {
                    $('#lgstIdShipModify').append(
                        "<option value='" + value.lgstId + "' lgstCode='" + value.lgstCode + "'>" + value.lgstName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

    //取得发货单数据
    var shiporderId = id;

    $.ajax({
        type: "GET",
        url: "/localshiporder/getShiporderInfo/" + shiporderId + ".action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,//同步
        success: function (data) {
            if (data.result == "success") {
                $("#lgstIdShipModify").val(data.data.lgstId);
                $("#lgstnoModify").val(data.data.lgstNo);
                $("#consModify").val(data.data.cons);
                $("#consTelModify").val(data.data.consTel);
                $("#consMobileModify").val(data.data.consMobile);
                $("#consAddrModify").val(data.data.consAddr);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

    $("#shipOrderIdModify").val(id);
    var editDialog = window.top.window.borrowCustomModalDialog($("#frmModifyShipOrder"));
    editDialog.modal({
        show : true,
        backdrop : 'static'
    });

}
// 设置高级查询条件
function setSearchCondition() {
    // 设置高级查询条件
    searchCondition = {
        "cons":encodeURI($('#cons').val()),
        "consMobile":encodeURI($('#consMobile').val()),
        "shopId":encodeURI($('#shopId').val()),
        "paidDateStart":encodeURI($('#paidDateStart').val()),
        "paidDateEnd":encodeURI($('#paidDatend').val()),
        "lgstNo":encodeURI($('#lgstNo').val()),
        "storId":encodeURI($('#storId').val()),
        "goodsCode":encodeURI($('#goodsCode').val()),
        "goodsName":encodeURI($('#goodsName').val()),
        "skuCode":encodeURI($('#skuCode').val()),
        "skuName":encodeURI($('#skuName').val()),
        "dateType":encodeURI($('#dateType').val()),
        "sendDateStart":encodeURI($('#sendDateStart').val()),
        "sendDatend":encodeURI($('#sendDatend').val())
    };
}

// 快速查询回车
$('#quickSearch').keydown(function(e){
    if (e.keyCode == 13 && $('#btnQuickSearch').is(":visible")) {
        $('#btnQuickSearch').click();
    }
});

// 快速查询按钮
$("#btnQuickSearch").click(function () {
    setSearchCondition();
    drawTable();
});

// 高级查询按钮
$("#advSearchSubmit").click(function () {
    setHidValue("frmAdvSearch");
    setSearchCondition();
    drawTable();
});

// 重置按钮
$("#advSearchReset").click(function() {
});

// 隐藏高级查询
$("#advSearchPanel").hide();
$("#btnAdvSearch").click(function () {
    if ($("#advSearchPanel").is(":hidden")) {
        $("#advSearchPanel").show();
        $("#btnQuickSearch").hide();
        $(this).children("i:eq(0)").removeClass("fa-angle-double-down");
        $(this).children("i:eq(0)").addClass("fa-angle-double-up");
    } else {
        $("#advSearchPanel").hide();
        $("#btnQuickSearch").show();
        $(this).children("i:eq(0)").removeClass("fa-angle-double-up");
        $(this).children("i:eq(0)").addClass("fa-angle-double-down");
    }
});

// 高级查询区域内单击
$("#advSearchPanel").click(function () {
})

// tab切换事件
$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
    
    switch ($(this).attr("id")) {
        case "waitSendOutGoods":  //待发货
            $("#batchCancel").show();
            $("#batchSystemSend").show();
            $("#batchConsign").hide();
            getWaitSendOutGoods();
            break;
        case "sendingOutGoods":  //发货中
            $("#batchCancel").show();
            $("#batchConsign").hide();
            $("#batchSystemSend").hide();
            getSendingOutGoods();
            break;
        case "shiped":  //已系统发货
            $("#batchCancel").hide();
            $("#batchConsign").show();
            $("#batchSystemSend").hide();
            getShiped();
            break;
        case "consigned":  //已平台发货
            $("#batchCancel").hide();
            $("#batchConsign").hide();
            $("#batchSystemSend").hide();
            getConsigned();
            break;
        case "canceled":  //已取消
            $("#batchCancel").hide();
            $("#batchConsign").hide();
            $("#batchSystemSend").hide();
            getCanceled();
            break;
        default:
            break;
    }
    
    getCounts();
});

// tab显示时
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    var tables = $.fn.dataTable.tables({
        visible : true,
        api : true
    });
    if (tables.length > 0) {
        $(tables).DataTable().columns.adjust();
    }
    $(tables).find("th.sorting_asc").removeClass("sorting_asc");
});

// 待发货列表
function getWaitSendOutGoods(){
    if (tblWaitSendOutGoods!=null && tblWaitSendOutGoods != undefined && ""!=tblWaitSendOutGoods){
        tblWaitSendOutGoods.draw();
        $("#chkAllWaitSendOutGoods").get(0).checked = false;
        return;
    }
    
    tblWaitSendOutGoods = $('#tblWaitSendOutGoods').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000] ],
        "dom": '<"bottom"rtflp>',
        "searching": false,
        "scrollX": true,
        "scrollCollapse": true,
        "pagingType": "full_numbers",
        "deferRender": true,
        "ajax": {
            "url": "/localshiporder/getShiporderList.action",
            "data": function (d) {
                d.shiporderStatus = "waitSendOutGoods";
                d.quickSearch = encodeURI($('#quickSearch').val());
                d.formJson = JSON.stringify(searchCondition);
            }
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [
        	{"data": "skuShow", "orderable": false},
            {"data": "shiporderId",
                "render": function ( data, type, row, meta ) {
                              var disabledStr = "";
                              if (row.lockStatus == "y") {
                                  disabledStr = ' disabled="disabled"';
                              }
                              return '<input shiporderId="' + row.shiporderId + '" type="checkbox"  style="" name="chkItemWaitSendOutGoods"' + disabledStr + ' value="" />';
                          },
            "orderable": false},
            {"data": "lockStatus", 
                "render": function ( data, type, row, meta ) {
                    if (row.lockStatus == "y") {
                        return '<span class="glyphicon glyphicon-lock"></span>';
                    } else {
                        return "&nbsp;";
                    }
                }
            },
            {"data": "shiporderCode"},
            // {"data": "wmsShiporderCode"},
            {"data": "sourceCode",
                "render": function ( data, type, row, meta ) {
                    var htmlName = "";
                    if (row.sourceType == "or") {
                        htmlName = "orderList.html";
                    } else {
                        htmlName = "afterSaleResend.html";
                    }
                    return '<a href="#" style="text-decoration:underline;" onclick="changeMenu(\'' + row.sourceCode + '\',\'' + htmlName + '\');">' + row.sourceCode + '</a>';
                },
            },
            {"data": "tradeCode"},
            {"data": "sourceType", 
                "render": function ( data, type, row, meta ) {
                    if (row.sourceType == "or") {
                        return "订单发货";
                    } else {
                        return "补发发货";
                    }
                }
            },
            {"data": "shopName"},
            {"data": "buyerNick"},
            {"data": "createTime"},
            {"data": "paidDate"},
            {"data": "operation", "orderable": false}
        ],
        "columnDefs": [
            {"className": "truncate-text tooltip-column-detail", "targets":[2]},
            {"className": "truncate-text tooltip-column-detail", "targets":[3]},
            {"className": "truncate-text tooltip-column-detail", "targets":[4]},
            {"className": "truncate-text tooltip-column-detail", "targets":[5]},
            {"className": "truncate-text tooltip-column-detail", "targets":[6]},
            {"className": "truncate-text tooltip-column-detail", "targets":[7]},
            {"className": "truncate-text tooltip-column-detail", "targets":[8]},
            {"className": "truncate-text tooltip-column-detail", "targets":[9]},
            {"className": "truncate-text tooltip-column-detail", "targets":[10]}
            // {"className": "truncate-text tooltip-column-detail", "targets":[11]}
        ],
        "order": [[10, "desc"]]
    }).on('draw.dt',  function() {
//       turn_on_iCheck($("#tblWaitSendOutGoods_wrapper"));
//        $("#chkAllWaitSendOutGoods").on("ifChanged", function() {
//            if ($("#chkAllWaitSendOutGoods").is(":checked")) {
//                $("#tblWaitSendOutGoods_wrapper").find(".icheck").iCheck("check");
//            } else {
//                $("#tblWaitSendOutGoods_wrapper").find(".icheck").iCheck("uncheck");
//            }
//        });
    });
    
    // 文字过长截断显示悬浮框
    $("#tblWaitSendOutGoods").tooltip({
        selector: ".tooltip-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
    
}

// 发货中列表
function getSendingOutGoods(){
    if (tblSendingOutGoods!=null && tblSendingOutGoods != undefined && ""!=tblSendingOutGoods){
        tblSendingOutGoods.draw();
        $("#chkAllSendingOutGoods").get(0).checked = false;
        showCancelRemark();
        return;
    }
    
    tblSendingOutGoods = $('#tblSendingOutGoods').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000] ],
        "dom": '<"bottom"rtflp>',
        "searching": false,
        "scrollX": true,
        "scrollCollapse": true,
        "pagingType": "full_numbers",
        "deferRender": true,
        "ajax": {
            "async": false,
            "url": "/localshiporder/getShiporderList.action",
            "data": function (d) {
                d.shiporderStatus = "sendingOutGoods";
                d.quickSearch = encodeURI($('#quickSearch').val());
                d.formJson = JSON.stringify(searchCondition);
            }
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [
        	{"data": "skuShow", "orderable": false},
            {"data": "shiporderId",
                "render": function ( data, type, row, meta ) {
                              var disabledStr = "";
                              if (row.lockStatus == "y") {
                                  disabledStr = ' disabled="disabled"';
                              }
                              return '<input shiporderId="' + row.shiporderId + '" type="checkbox"  style="" name="chkItemSendingOutGoods"' + disabledStr + ' value="" />';
                          },
            "orderable": false},
            {"data": "cancelStatus", 
                "render": function ( data, type, row, meta ) {
                    if (row.cancelStatus == "n") {
                        return "未取消";
                    } else if (row.cancelStatus == "r") {
                        return "申请取消";
                    } else if (row.cancelStatus == "f") {
                        return "取消失败";
                    }
                }
            },
            {"data": "lockStatus", 
                "render": function ( data, type, row, meta ) {
                    if (row.lockStatus == "y") {
                        return '<span class="glyphicon glyphicon-lock"></span>';
                    } else {
                        return "&nbsp;";
                    }
                }
            },
            {"data": "shiporderCode"},
            // {"data": "wmsShiporderCode"},
            {"data": "sourceCode",
                "render": function ( data, type, row, meta ) {
                    var htmlName = "";
                    if (row.sourceType == "or") {
                        htmlName = "orderList.html";
                    } else {
                        htmlName = "afterSaleResend.html";
                    }
                    return '<a href="#" style="text-decoration:underline;" onclick="changeMenu(\'' + row.sourceCode + '\',\'' + htmlName + '\');">' + row.sourceCode + '</a>';
                },
            },
            {"data": "tradeCode"},
            {"data": "sourceType", 
                "render": function ( data, type, row, meta ) {
                    if (row.sourceType == "or") {
                        return "订单发货";
                    } else {
                        return "补发发货";
                    }
                }
            },
            {"data": "shopName"},
            {"data": "buyerNick"},
            {"data": "createTime"},
            {"data": "paidDate"},
            {"data": "operation", "orderable": false},
            {"data": "cancelRemark", "visible": false},
            {"data": "storCode", "visible": false},
            {"data": "entId", "visible": false},
            {"data": "storId", "visible": false},
            {"data": "prjId", "visible": false},
            {"data": "sourceId", "visible": false}
        ],
        "columnDefs": [
            {"className": "truncate-text tooltip-column-detail", "targets":[3]},
            {"className": "truncate-text tooltip-column-detail", "targets":[4]},
            {"className": "truncate-text tooltip-column-detail", "targets":[5]},
            {"className": "truncate-text tooltip-column-detail", "targets":[6]},
            {"className": "truncate-text tooltip-column-detail", "targets":[7]},
            {"className": "truncate-text tooltip-column-detail", "targets":[8]},
            {"className": "truncate-text tooltip-column-detail", "targets":[9]},
            {"className": "truncate-text tooltip-column-detail", "targets":[10]},
            {"className": "truncate-text tooltip-column-detail", "targets":[11]}
            // {"className": "truncate-text tooltip-column-detail", "targets":[12]}
        ],
        "order": [[11, "desc"]]
    }).on('draw.dt',  function() {
        
//       turn_on_iCheck($("#divSendingOutGoods"));
//        $("#chkAllSendingOutGoods").on("ifChanged", function() {
//            if ($("#chkAllSendingOutGoods").is(":checked")) {
//                $("#divSendingOutGoods").find(".icheck").iCheck("check");
//            } else {
//                $("#divSendingOutGoods").find(".icheck").iCheck("uncheck");
//            }
//        });
    });
    
    showCancelRemark();
    
    // 文字过长截断显示悬浮框
    $("#tblSendingOutGoods").tooltip({
        selector: ".tooltip-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
  
}

// 已系统发货列表
function getShiped(){
    if (tblShiped!=null && tblShiped != undefined && ""!=tblShiped){
        tblShiped.draw();
        $("#chkAllShiped").get(0).checked = false;
        return;
    }
    
    tblShiped = $('#tblShiped').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000] ],
        "dom": '<"bottom"rtflp>',
        "searching": false,
        "scrollX": true,
        "scrollCollapse": true,
        "pagingType": "full_numbers",
        "deferRender": true,
        "ajax": {
            "url": "/localshiporder/getShiporderList.action",
            "data": function (d) {
                d.shiporderStatus = "shiped";
                d.quickSearch = encodeURI($('#quickSearch').val());
                d.formJson = JSON.stringify(searchCondition);
            }
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [
        	{"data": "skuShow", "orderable": false},
            {"data": "shiporderId",
                "render": function ( data, type, row, meta ) {
                              var disabledStr = "";
                              if (row.lockStatus=="y" || row.sourceType=="rs") {
                                  disabledStr = ' disabled="disabled"';
                              }
                              return '<input shiporderId="' + row.shiporderId + '" type="checkbox"  style="" name="chkItemShiped"' + disabledStr + ' value="" />';
                          },
            "orderable": false},
            {"data": "lockStatus", 
                "render": function ( data, type, row, meta ) {
                    if (row.lockStatus == "y") {
                        return '<span class="glyphicon glyphicon-lock"></span>';
                    } else {
                        return "&nbsp;";
                    }
                }
            },
            {"data": "shiporderCode"},
            // {"data": "wmsShiporderCode"},
            {"data": "sourceCode",
                "render": function ( data, type, row, meta ) {
                    var htmlName = "";
                    if (row.sourceType == "or") {
                        htmlName = "orderList.html";
                    } else {
                        htmlName = "afterSaleResend.html";
                    }
                    return '<a href="#" style="text-decoration:underline;" onclick="changeMenu(\'' + row.sourceCode + '\',\'' + htmlName + '\');">' + row.sourceCode + '</a>';
                },
            },
            {"data": "tradeCode"},
            {"data": "sourceType", 
                "render": function ( data, type, row, meta ) {
                    if (row.sourceType == "or") {
                        return "订单发货";
                    } else {
                        return "补发发货";
                    }
                }
            },
            {"data": "shopName"},
            {"data": "buyerNick"},
            {"data": "createTime"},
            {"data": "paidDate"},
            {"data": "shipTime"},
            {"data": "operation", "orderable": false},
            {"data": "tradeCode", "visible": false},
            {"data": "lgstNo", "visible": false},
            {"data": "lgstCode", "visible": false},
            {"data": "shopId", "visible": false}
        ],
        "columnDefs": [
            {"className": "truncate-text tooltip-column-detail", "targets":[2]},
            {"className": "truncate-text tooltip-column-detail", "targets":[3]},
            {"className": "truncate-text tooltip-column-detail", "targets":[4]},
            {"className": "truncate-text tooltip-column-detail", "targets":[5]},
            {"className": "truncate-text tooltip-column-detail", "targets":[6]},
            {"className": "truncate-text tooltip-column-detail", "targets":[7]},
            {"className": "truncate-text tooltip-column-detail", "targets":[8]},
            {"className": "truncate-text tooltip-column-detail", "targets":[9]},
            {"className": "truncate-text tooltip-column-detail", "targets":[10]},
            {"className": "truncate-text tooltip-column-detail", "targets":[11]}
        ],
        "order": [[10, "desc"]]
    }).on('draw.dt',  function() {
//       turn_on_iCheck($("#tblShiped_wrapper"));
//        $("#chkAllShiped").on("ifChanged", function() {
//            if ($("#chkAllShiped").is(":checked")) {
//                $("#tblShiped_wrapper").find(".icheck").iCheck("check");
//            } else {
//                $("#tblShiped_wrapper").find(".icheck").iCheck("uncheck");
//            }
//        });
    });
    
    // 文字过长截断显示悬浮框
    $("#tblShiped").tooltip({
        selector: ".tooltip-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
    
}

// 已平台发货列表
function getConsigned(){
    if (tblConsigned!=null && tblConsigned != undefined && ""!=tblConsigned){
        tblConsigned.draw();
//        $("#chkAllConsigned").get(0).checked = false;
        return;
    }
    
    tblConsigned = $('#tblConsigned').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000] ],
        "dom": '<"bottom"rtflp>',
        "searching": false,
        "scrollX": true,
        "scrollCollapse": true,
        "pagingType": "full_numbers",
        "deferRender": true,
        "ajax": {
            "url": "/localshiporder/getShiporderList.action",
            "data": function (d) {
                d.shiporderStatus = "consigned";
                d.quickSearch = encodeURI($('#quickSearch').val());
                d.formJson = JSON.stringify(searchCondition);
            }
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [
        	{"data": "skuShow", "orderable": false},
            {"data": "lockStatus", 
                "render": function ( data, type, row, meta ) {
                    if (row.lockStatus == "y") {
                        return '<span class="glyphicon glyphicon-lock"></span>';
                    } else {
                        return "&nbsp;";
                    }
                }
            },
            {"data": "shiporderCode"},
            // {"data": "wmsShiporderCode"},
            {"data": "sourceCode",
                "render": function ( data, type, row, meta ) {
                    var htmlName = "";
                    if (row.sourceType == "or") {
                        htmlName = "orderList.html";
                    } else {
                        htmlName = "afterSaleResend.html";
                    }
                    return '<a href="#" style="text-decoration:underline;" onclick="changeMenu(\'' + row.sourceCode + '\',\'' + htmlName + '\');">' + row.sourceCode + '</a>';
                },
            },
            {"data": "tradeCode"},
            {"data": "sourceType", 
                "render": function ( data, type, row, meta ) {
                    if (row.sourceType == "or") {
                        return "订单发货";
                    } else {
                        return "补发发货";
                    }
                }
            },
            {"data": "shopName"},
            {"data": "buyerNick"},
            {"data": "createTime"},
            {"data": "paidDate"},
            {"data": "consignTime"}
        ],
        "columnDefs": [
        	{"className": "truncate-text tooltip-column-detail", "targets":[1]},
            {"className": "truncate-text tooltip-column-detail", "targets":[2]},
            {"className": "truncate-text tooltip-column-detail", "targets":[3]},
            {"className": "truncate-text tooltip-column-detail", "targets":[4]},
            {"className": "truncate-text tooltip-column-detail", "targets":[5]},
            {"className": "truncate-text tooltip-column-detail", "targets":[6]},
            {"className": "truncate-text tooltip-column-detail", "targets":[7]},
            {"className": "truncate-text tooltip-column-detail", "targets":[8]},
            {"className": "truncate-text tooltip-column-detail", "targets":[9]},
            {"className": "truncate-text tooltip-column-detail", "targets":[10]}
            // {"className": "truncate-text tooltip-column-detail", "targets":[11]},
        ],
        "order": [[10, "desc"]]
    }).on('draw.dt',  function() {
//       turn_on_iCheck($("#tblConsigned_wrapper"));
//        $("#chkAllConsigned").on("ifChanged", function() {
//            if ($("#chkAllConsigned").is(":checked")) {
//                $("#tblConsigned_wrapper").find(".icheck").iCheck("check");
//            } else {
//                $("#tblConsigned_wrapper").find(".icheck").iCheck("uncheck");
//            }
//        });
    });
    
    // 文字过长截断显示悬浮框
    $("#tblConsigned").tooltip({
        selector: ".tooltip-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
    
}

// 已取消列表
function getCanceled(){
    if (tblCanceled!=null && tblCanceled != undefined && ""!=tblCanceled){
        tblCanceled.draw();
        return;
    }
    
    tblCanceled = $('#tblCanceled').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000] ],
        "dom": '<"bottom"rtflp>',
        "searching": false,
        "scrollX": true,
        "scrollCollapse": true,
        "pagingType": "full_numbers",
        "deferRender": true,
        "ajax": {
            "url": "/localshiporder/getShiporderList.action",
            "data": function (d) {
                d.shiporderStatus = "canceled";
                d.quickSearch = encodeURI($('#quickSearch').val());
                d.formJson = JSON.stringify(searchCondition);
            }
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [
            {"data": "skuShow", "orderable": false},
            {"data": "lockStatus", 
                "render": function ( data, type, row, meta ) {
                    if (row.lockStatus == "y") {
                        return '<span class="glyphicon glyphicon-lock"></span>';
                    } else {
                        return "&nbsp;";
                    }
                }
            },
            {"data": "shiporderCode"},
            // {"data": "wmsShiporderCode"},
            {"data": "sourceCode",
                "render": function ( data, type, row, meta ) {
                    var htmlName = "";
                    if (row.sourceType == "or") {
                        htmlName = "orderList.html";
                    } else {
                        htmlName = "afterSaleResend.html";
                    }
                    return '<a href="#" style="text-decoration:underline;" onclick="changeMenu(\'' + row.sourceCode + '\',\'' + htmlName + '\');">' + row.sourceCode + '</a>';
                },
            },
            {"data": "tradeCode"},
            {"data": "sourceType", 
                "render": function ( data, type, row, meta ) {
                    if (row.sourceType == "or") {
                        return "订单发货";
                    } else {
                        return "补发发货";
                    }
                }
            },
            {"data": "shipmentsStatus"},
            {"data": "shopName"},
            {"data": "buyerNick"},
            {"data": "createTime"},
            {"data": "paidDate"}
        ],
        "columnDefs": [
            {"className": "truncate-text tooltip-column-detail", "targets":[1]},
            {"className": "truncate-text tooltip-column-detail", "targets":[2]},
            {"className": "truncate-text tooltip-column-detail", "targets":[3]},
            {"className": "truncate-text tooltip-column-detail", "targets":[4]},
            {"className": "truncate-text tooltip-column-detail", "targets":[5]},
            {"className": "truncate-text tooltip-column-detail", "targets":[6]},
            {"className": "truncate-text tooltip-column-detail", "targets":[7]},
            {"className": "truncate-text tooltip-column-detail", "targets":[8]},
            {"className": "truncate-text tooltip-column-detail", "targets":[9]},
            {"className": "truncate-text tooltip-column-detail", "targets":[10]}
            // {"className": "truncate-text tooltip-column-detail", "targets":[11]}
        ],
        "order": [[10, "desc"]]
    });
    
    // 文字过长截断显示悬浮框
    $("#tblCanceled").tooltip({
        selector: ".tooltip-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
    
}

// 取得tab上面的条数
function getCounts(){
    var data =  {quickSearch:encodeURI($('#quickSearch').val()), formJson:JSON.stringify(searchCondition)};
    
    $.ajax({
        type: "GET",
        url: "/localshiporder/getShiporderListCount.action",
        data: data,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data.result == "success") {
                $("#waitSendOutGoods").html("待发货(" + data.waitSendOutGoodsCount + ")");
                $("#sendingOutGoods").html("发货中(" + data.sendingOutGoodsCount + ")");
                $("#shiped").html("已系统发货(" + data.shipedCount + ")");
                $("#consigned").html("已平台发货(" + data.consignedCount + ")");
                $("#canceled").html("已取消(" + data.canceledCount + ")");
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

// 子表格显示隐藏
$('.tablefirst tbody').on('click', 'td .sku-show', function () {
    var shiporderId = $(this).attr('shiporderId');
    var tr = $(this).closest('tr');
    var table;
    var row;
    var tablename =  "";
    $("div .active").each(function(){
        switch ($(this).attr("id")) {
        case "divWaitSendOutGoods":
            table = tblWaitSendOutGoods;
            row = tblWaitSendOutGoods.row(tr);
            tablename = "tblWaitSendOutGoods";
            break;
        case "divSendingOutGoods":
            table = tblSendingOutGoods;
            row = tblSendingOutGoods.row(tr);
            tablename = "tblSendingOutGoods";
            break;
        case "divShiped":
            table = tblShiped;
            row = tblShiped.row(tr);
            tablename = "tblShiped"
            break;
        case "divConsigned":
            table = tblConsigned;
            row = tblConsigned.row(tr);
            tablename = "tblConsigned";
            break;
        case "divCanceled":
            table = tblCanceled;
            row = tblCanceled.row(tr);
            tablename = "tblCanceled";
            break;
        default:
            break;
        }
    });
    // 加载过，而且是显示的状态
    if ( row.child.isShown() ) {
        row.child.hide();
        tr.removeClass('shown');
        $(this).removeClass('fa-chevron-up');
        $(this).addClass('fa-chevron-down');
    } else {
        // 关闭其他
        $('#'+tablename+' tbody tr').each(function(){
            if ($(this).attr("role")=="row"){
                table.row($(this)).child.hide();
            }
        });
        $('.fa-chevron-up').addClass('fa-chevron-down');
        $('.fa-chevron-down').removeClass('fa-chevron-up');
        
        var temp = '<iframe id="contentFrame" name="contentFrame" style="width:100%;" frameborder="0" scrolling="auto" src="/views/warehouse/local/localShipOrder/localsonShiporderList.html" width="100%" height="245"></iframe>';
        row.child(temp).show();
        tr.addClass('shown');
        $(this).addClass('fa-chevron-up');
        $(this).removeClass('fa-chevron-down');
        
        $('#shiporderId').val(shiporderId);
    }
});

// 改变菜单选中状态
function changeMenu(sourceCode, htmlName) {
    window.top.window.$('a').each(function() {
        var str = $(this).attr("onclick");
        if (str != undefined && str.indexOf(htmlName) > 0) {
            var resendTagName = "系统补发单";
            window.top.window.$("#orderCode").val(sourceCode);
            $(this).parents(':eq(2)').children('a').get(0).click();
            $(this).click();
            var resendIframe = window.top.window.getIframeByTabName(resendTagName);
            if (resendIframe&&resendIframe.contentWindow.document.body.innerHTML != "") { // 页面已经打开过
                window.top.window.refreshTabByTabName(resendTagName);
            }
            return false;
        }
    });
}

// 取消发货单
function operationCancel(btnCancel) {
    var trNode = btnCancel.parentNode.parentNode;
    var rowData = null;
    var shiporderStatus = getShiporderStatus();
    if (shiporderStatus == "waitSendOutGoods") {
        rowData = tblWaitSendOutGoods.row(trNode).data();
    } else if (shiporderStatus == "sendingOutGoods") {
        rowData = tblSendingOutGoods.row(trNode).data();
    }
    var data = {
        "shiporderId": encodeURI($(btnCancel).attr("shiporderId")),
        "shiporderStatus": encodeURI(shiporderStatus),
        "sourceType": encodeURI(rowData.sourceType),
        "storCode": encodeURI(rowData.storCode),
        "qmOwnercode": encodeURI(rowData.qmOwnercode),
        "wmsShiporderCode": encodeURI(rowData.wmsShiporderCode),
        "entId": encodeURI(rowData.entId),
        "storId": encodeURI(rowData.storId),
        "prjId": encodeURI(rowData.prjId),
        "sourceId": encodeURI(rowData.sourceId)
    }
    
    $.ajax({
        type: "POST",
        url: "/localshiporder/cancelShiporder.action",
        data: JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (json) {
            if (json.result=="success") {
                window.top.window.showModalAlert(json.data);
                drawTable();
            } else {
                window.top.window.showModalAlert(json.msg);
            }
        }
    });
}

// 全选，全不选商品
// 待发货
$("#chkAllWaitSendOutGoods").click(function () {
    checkItemAll($("#chkAllWaitSendOutGoods"), 'chkItemWaitSendOutGoods');
});

// 发货中
$("#chkAllSendingOutGoods").click(function () {
    checkItemAll($("#chkAllSendingOutGoods"), 'chkItemSendingOutGoods');
});

// 已系统发货
$("#chkAllShiped").click(function () {
    checkItemAll($("#chkAllShiped"), 'chkItemShiped');
});
 
// 已平台发货
//$("#chkAllConsigned").click(function () {
//    checkItemAll($("#chkAllConsigned"), 'chkItemConsigned');
//});

// 全选，全不选商品共通
function checkItemAll(checkboxAllObj, checkboxItemName) {
    var checkboxes = document.getElementsByName(checkboxItemName);
    for (var i = 0; i < checkboxes.length; i++) {
        var checkbox = checkboxes[i];
        if (!checkboxAllObj.get(0).checked) {
            checkbox.checked = false;
        } else {
            if ($(checkbox).prop("disabled") == false) {
                checkbox.checked = true;
            }
        }
    }
}

// 得到发货状态
function getShiporderStatus() {
    var shiporderStatus = "";
    $("div .active").each(function(){
        switch ($(this).attr("id")) {
            case "divWaitSendOutGoods":  //待发货
                shiporderStatus = "waitSendOutGoods";
                break;
            case "divSendingOutGoods":  //发货中
                shiporderStatus = "sendingOutGoods";
                break;
            case "divShiped":  //已系统发货
                shiporderStatus = "shiped";
                break;
            case "divConsigned":  //已平台发货
                shiporderStatus = "consigned";
                break;
            case "divCanceled":  //已取消
                shiporderStatus = "canceled";
                break;
            default:
                break;
        }
    });
    
    return shiporderStatus;
}

// 重画表格
function drawTable() {
    $("div .active").each(function(){
        switch ($(this).attr("id")) {
            case "divWaitSendOutGoods":  //待发货
                tblWaitSendOutGoods.draw();
                $("#chkAllWaitSendOutGoods").get(0).checked = false;
                break;
            case "divSendingOutGoods":  //发货中
                tblSendingOutGoods.draw();
                $("#chkAllSendingOutGoods").get(0).checked = false;
                showCancelRemark();
                break;
            case "divShiped":  //已系统发货
                tblShiped.draw();
                $("#chkAllShiped").get(0).checked = false;
                break;
            case "divConsigned":  //已平台发货
                tblConsigned.draw();
//                $("#chkAllConsigned").get(0).checked = false;
                break;
            case "divCanceled":  //已取消
                tblCanceled.draw();
                break;
            default:
                break;
        }
    });
    
    getCounts();
}

// 批量取消
function batchCancel() {
    var shiporderVOList = new Array();
    var shiporderStatus = getShiporderStatus();
    var chkItem = null;
    if (shiporderStatus == "waitSendOutGoods") {
        chkItem = $('input:checkbox[name=chkItemWaitSendOutGoods]')
    } else if (shiporderStatus == "sendingOutGoods") {
        chkItem = $('input:checkbox[name=chkItemSendingOutGoods]')
    } else {
        return;
    } 
    chkItem.each(function() {
        if ($(this).get(0).checked) {
            var trNode = this.parentNode.parentNode;
            var rowData = null;
            if (shiporderStatus == "waitSendOutGoods") {
                rowData = tblWaitSendOutGoods.row(trNode).data();
            } else if (shiporderStatus == "sendingOutGoods") {
                rowData = tblSendingOutGoods.row(trNode).data();
            }
            var data = {
                "shiporderId": encodeURI($(this).attr("shiporderId")),
                "shiporderStatus": encodeURI(shiporderStatus),
                "sourceType": encodeURI(rowData.sourceType),
                "storCode": encodeURI(rowData.storCode),
                "qmOwnercode": encodeURI(rowData.qmOwnercode),
                "wmsShiporderCode": encodeURI(rowData.wmsShiporderCode),
                "entId": encodeURI(rowData.entId),
                "storId": encodeURI(rowData.storId),
                "prjId": encodeURI(rowData.prjId),
                "sourceId": encodeURI(rowData.sourceId)
            }
            shiporderVOList.push(data);
        }
    });
    
    if(shiporderVOList.length == 0) {           
        return window.top.window.showModalAlert("请选中一条数据");
    }

    $.ajax({
        type : "post",
        url : "/localshiporder/batchCancel.action",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(shiporderVOList),
        traditional : true,
        async : false, // 同步
        success : function(json) {
            if (json.result=="success") {
                window.top.window.showModalAlert("取消成功");
            } else {
                window.top.window.showModalAlert(json.msg);
            }
            drawTable();
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

// 平台发货
function operationConsign(btnConsign) {
    var trNode = btnConsign.parentNode.parentNode;
    var rowData = tblShiped.row(trNode).data();
    var data = {
        "shiporderId": encodeURI($(btnConsign).attr("shiporderId")),
        "tradeCode": encodeURI(rowData.tradeCode),
        "lgstNo": encodeURI(rowData.lgstNo),
        "lgstCode": encodeURI(rowData.lgstCode),
        "shopId": encodeURI(rowData.shopId),
        "shiporderCode": encodeURI(rowData.shiporderCode),
        "sourceCode": encodeURI(rowData.sourceCode)
    }
    
    $.ajax({
        type: "POST",
        url: "/localshiporder/consign.action",
        data: JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (json) {
            if (json.result=="success") {
                window.top.window.showModalAlert(json.data);
            } else {
                window.top.window.showModalAlert(json.msg);
            }
            drawTable();
        }
    });
}

//批量系统发货
function batchSystemSend(){
    var chkItem = null;
    var shiporderStatus = getShiporderStatus();
    if (shiporderStatus == "waitSendOutGoods") {
        chkItem = $('input:checkbox[name=chkItemWaitSendOutGoods]')
    } else {
        return;
    }
    var shiporderVOList = new Array();
    chkItem.each(function() {
        if ($(this).get(0).checked) {
            var trNode = this.parentNode.parentNode;
            var rowData = tblWaitSendOutGoods.row(trNode).data();
            var data = {
                "shiporderId": encodeURI($(this).attr("shiporderId"))
                // "tradeCode": encodeURI(rowData.tradeCode),
                // "lgstNo": encodeURI(rowData.lgstNo),
                // "lgstCode": encodeURI(rowData.lgstCode),
                // "shopId": encodeURI(rowData.shopId),
                // "shiporderCode": encodeURI(rowData.shiporderCode),
                // "sourceCode": encodeURI(rowData.sourceCode)
            }
            shiporderVOList.push(data);
        }
    });
    if(shiporderVOList.length == 0) {
        return window.top.window.showModalAlert("请选中一条数据");
    }

    $.ajax({
        type : "post",
        url : "/localshiporder/batchSystemSend.action",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(shiporderVOList),
        traditional : true,
        async : false, // 同步
        success : function(json) {
            if (json.result=="success") {
                window.top.window.showModalAlert("操作成功");
            } else {
                var reg = new RegExp(/\\n/,"g");
                window.top.window.showModalAlert(json.msg.replace(reg, "\r"));
            }
            drawTable();
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

}
// 批量平台发货
function batchConsign() {
    var shiporderStatus = getShiporderStatus();
    
    var shiporderVOList = new Array();
    var chkItem = null;
    if (shiporderStatus == "shiped") {
        chkItem = $('input:checkbox[name=chkItemShiped]')
    } else {
        return;
    } 
    chkItem.each(function() {
        if ($(this).get(0).checked) {
            var trNode = this.parentNode.parentNode;
            var rowData = tblShiped.row(trNode).data();
            var data = {
                "shiporderId": encodeURI($(this).attr("shiporderId")),
                "tradeCode": encodeURI(rowData.tradeCode),
                "lgstNo": encodeURI(rowData.lgstNo),
                "lgstCode": encodeURI(rowData.lgstCode),
                "shopId": encodeURI(rowData.shopId),
                "shiporderCode": encodeURI(rowData.shiporderCode),
                "sourceCode": encodeURI(rowData.sourceCode)
            }
            shiporderVOList.push(data);
        }
    });
    
    if(shiporderVOList.length == 0) {           
        return window.top.window.showModalAlert("请选中一条数据");
    }
    
    $.ajax({
        type : "post",
        url : "/localshiporder/batchConsign.action",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(shiporderVOList),
        traditional : true,
        async : false, // 同步
        success : function(json) {
            if (json.result=="success") {
                window.top.window.showModalAlert(json.data);
            } else {
                window.top.window.showModalAlert(json.msg);
            }
            drawTable();
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

// 显示取消失败原因
function showCancelRemark() {
    $("#tblSendingOutGoods tbody tr").each(function() {
        var rowData = tblSendingOutGoods.row(this).data();
        if (rowData != undefined && rowData.cancelStatus == "f") {
            $(this).find("td").eq(2).attr("title", rowData.cancelRemark);
        }
    });
}

// 导出
function exportShiporder() {
}

// 刷新
function refresh() {   
    refreshCheck();
    drawTable();
}
//刷新高级查询和快速查询
function refreshCheck(){
	$('#quickSearch').val("");
    $("#advSearchReset").click();
    searchCondition = {};
    if (!$("#advSearchPanel").is(":hidden")){
        $("#btnAdvSearch").click();   
    } 
}